package com.malou.client.ventas.proveedor;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.binding.FieldBinding;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Status;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.HiddenField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.Validator;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.toolbar.FillToolItem;
import com.google.gwt.core.client.GWT;
import com.malou.client.MalouConstants;
import com.malou.client.util.ComboboxFieldBinding;

public class ProveedorDialog extends Dialog{

	 protected HiddenField<String> id;
	 protected TextField<String> razonsocial;
	 protected TextField<String> representantelegal;
	 protected TextField<String> ruc;
	 protected TextField<String> dni;
	 protected TextField<String> telefono;
	 protected TextField<String> celular;
	 protected TextField<String> direccion;
	 protected TextField<String> email;
	 protected TextField<String> descripcion;
	 private ComboBox<BeanModel> tipo;	 
	 protected Button cancelar;
	 protected Button guardar;
	 protected Status status;
	  
	 private FormBinding formBindings;
	 Proveedor prv; 
	  
      //estoy creando un objeto, no lo hago con new porque MalouConstans es una interface.
	  private MalouConstants constants = GWT.create(MalouConstants.class);
	 
	  public ProveedorDialog(){
		 
	    setLayout(new FitLayout());
		setModal(true);
		setPlain(true);
			
		setSize(450, 350);
		setClosable(true);
			
		FormPanel panel = new FormPanel();		
		panel.setBorders(false);
		panel.setBodyBorder(false);
		panel.setPadding(5);
		panel.setHeaderVisible(false);
		panel.setLabelWidth(110);
		    
		formBindings = new FormBinding(panel, false);	    
		addFields(panel);
		    
		setButtonAlign(HorizontalAlignment.LEFT);
		setButtons("");
		add(panel);
		    
		setBodyBorder(true);	    
		setResizable(false);	    
		setFocusWidget(razonsocial);
	 }
	 
	  @Override
	  protected void createButtons() {
	    super.createButtons();
	    
	    if (constants == null) {
	    	constants = GWT.create(MalouConstants.class);
		}
	    //status es para mostrar el icono de cargando, al costado de los botones del dialogo
	    status = new Status();
	    status.setBusy(constants.guardando());
	    status.hide();
	    status.setAutoWidth(true);
	    getButtonBar().add(status);
	    
	    getButtonBar().add(new FillToolItem());
	    
	    cancelar = new Button(constants.cancelar());
	    
	    cancelar.addSelectionListener(new SelectionListener<ButtonEvent>() {
	      public void componentSelected(ButtonEvent ce) {
	    	  ProveedorDialog.this.hide();
	      }

	    });

	    guardar = new Button(constants.guardar());
	    
	    guardar.addSelectionListener(new SelectionListener<ButtonEvent>() {
	      public void componentSelected(ButtonEvent ce) {
	    	  if(validate()){
	    		status.show();
    		    getButtonBar().disable();
    		    
    			prv = new Proveedor();
    			if(id.getValue() != null)
    			prv.setId(Integer.valueOf(id.getValue()));
    			prv.setRazonsocial(razonsocial.getValue());
    			prv.setRepresentantelegal(representantelegal.getValue());
    			prv.setRuc(ruc.getValue());
				prv.setDni(dni.getValue());
				prv.setTelefono(telefono.getValue());
				prv.setCelular(celular.getValue());
				prv.setDireccion(direccion.getValue());
				prv.setEmail(email.getValue());
	            prv.setDescripcion(descripcion.getValue());
	            if(tipo.getValue().get("id") != null)
	            	prv.setTipoproveedor_id(Integer.parseInt(tipo.getValue().get("id").toString()));
	       			
    			Proveedores.proveedorDialog = ProveedorDialog.this;
    			Proveedores.save(prv);		    			
	    	  }	    		  
	    		 
	    	  
	      }
	    });
	    
	    addButton(guardar);
	    addButton(cancelar);	    
	    
	  }

	  protected boolean validate() {
			boolean rs    = razonsocial.isValid();
			boolean rl    = representantelegal.isValid();
			boolean rc   = ruc.isValid();
			boolean dn   = dni.isValid();
			boolean tlf   = telefono.isValid();
			boolean cel   = celular.isValid();
			boolean dir   = direccion.isValid();
			boolean ema = email.isValid();
			boolean desc  = descripcion.isValid();
			boolean tip   = tipo.isValid();
			
		    return rs && rl && rc && dn && tlf && cel && dir && ema && desc && tip;
		  }
	  
	  private void addFields(ContentPanel cp) {

			id = new HiddenField<String>();
			id.setVisible(false);
			cp.add(id);
			
			razonsocial = new TextField<String>();
		    razonsocial.setMinLength(3);
		    razonsocial.setFieldLabel(constants.proveedorRazonSocial());	    
		    razonsocial.setAllowBlank(false);	    
		    cp.add(razonsocial, new FormData("-20"));
		    
		    representantelegal = new TextField<String>();
		    representantelegal.setMinLength(4);
		    representantelegal.setFieldLabel(constants.proveedorRepresentanteLegal());	    
		    representantelegal.setAllowBlank(true);
		    cp.add(representantelegal, new FormData("-20"));	       

		    ruc = new TextField<String>();
		    ruc.setMinLength(11);
		    ruc.setMaxLength(11);
		    ruc.setFieldLabel(constants.proveedorRuc());	    
		    ruc.setAllowBlank(false);
		    cp.add(ruc, new FormData("-20"));
		    
		    dni = new TextField<String>();
		    dni.setMinLength(8);
		    dni.setMaxLength(8);
		    dni.setFieldLabel(constants.proveedorDni());	    
		    dni.setAllowBlank(true);//funcion que te permite vacios
		    cp.add(dni, new FormData("-20"));
		    	    
		    telefono = new TextField<String>();
		    telefono.setMinLength(3);	    
		    telefono.setFieldLabel(constants.proveedorTelefono());	    
		    cp.add(telefono, new FormData("-20"));
		    
		    celular = new TextField<String>();
		    celular.setMinLength(3);	    
		    celular.setFieldLabel(constants.proveedorCelular());	    
		    cp.add(celular, new FormData("-20"));
		    
		    direccion = new TextField<String>();
		    direccion.setMinLength(3);	    
		    direccion.setFieldLabel(constants.proveedorDireccion());	    
		    cp.add(direccion, new FormData("-20"));
		    
		    email = new TextField<String>();
		    email.setMinLength(3);	    
		    email.setFieldLabel(constants.proveedorEmail());
		    
		    final String emailReg = "[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}";
		    final String errMsg = constants.emailNoValido();
		    email.setValidator(new Validator() {
		      public String validate(Field<?> field, String value) {
		        if (!value.toUpperCase().matches(emailReg))
		          return errMsg;
		        return null;
		      }
		    });
		    
		    cp.add(email, new FormData("-20"));
		    
		    descripcion = new TextField<String>();
		    descripcion.setMinLength(3);	    
		    descripcion.setFieldLabel(constants.proveedorDescripcion());	    
		    cp.add(descripcion, new FormData("-20"));
		    
		    Proveedores.getComboProveedores();
		    Proveedores.loaderTipoProveedor.load();
		    
		    tipo = new ComboBox<BeanModel>();  
		    tipo.setEditable(false);
			tipo.setFieldLabel(constants.proveedorTipo());
			tipo.setDisplayField("descripcion");
			tipo.setEmptyText("Seleccione...");
			tipo.setWidth(150);  
			tipo.setStore(Proveedores.storeTipoProveedor);  
			tipo.setTypeAhead(true);  
			tipo.setTriggerAction(TriggerAction.ALL);
			tipo.setValueField("descripcion");
			tipo.setAllowBlank(false);
		    cp.add(tipo, new FormData("-20"));
		    
		  }
	  
	  public void reset(){
		  setIconStyle("icon-new");
		  setHeading(constants.proveedorNuevoProveedor());
		  		  
		  id.clear();
		  razonsocial.clear();
		  representantelegal.clear();
		  ruc.clear();
		  dni.clear();
		  telefono.clear();
		  celular.clear();
		  direccion.clear();
		  email.clear();
		  descripcion.clear();		 
		  status.hide();
		  getButtonBar().enable();
	  }
	  
	  public void setStore(ListStore<BeanModel> store){
		  //fieldBinding(campo caja de texto,campo de la clase)
		  //el bindig solo se utiliza para editar y no para agregar cuando se seniala la tabla aparece llenado el formulario emergente
		  //entonces el binding enlaza la tabla con el formulario emergente
		  formBindings.addFieldBinding(new FieldBinding(id, "id"));
		  formBindings.addFieldBinding(new FieldBinding(razonsocial, "razonsocial"));
		  formBindings.addFieldBinding(new FieldBinding(representantelegal, "representantelegal"));
		  formBindings.addFieldBinding(new FieldBinding(ruc, "ruc"));
		  formBindings.addFieldBinding(new FieldBinding(dni, "dni"));
		  formBindings.addFieldBinding(new FieldBinding(telefono, "telefono"));
		  formBindings.addFieldBinding(new FieldBinding(celular, "celular"));
		  formBindings.addFieldBinding(new FieldBinding(direccion, "direccion"));
		  formBindings.addFieldBinding(new FieldBinding(email, "email"));
		  formBindings.addFieldBinding(new FieldBinding(descripcion, "descripcion"));
		  formBindings.addFieldBinding(new ComboboxFieldBinding(tipo, "tipo"));		  
		  formBindings.setStore(store);
	  }
	  
	  public void beforeEdit(){
		  setIconStyle("icon-update");
		  setHeading(constants.proveedorModificarProveedor());		  
		  
		  status.hide();
		  getButtonBar().enable();
	  }
	  public void bind(BeanModel selectedModel){		  
		  formBindings.bind(selectedModel);
	  }
	  public void unbind(){
		  formBindings.unbind();
	  }
	  
 }